package com.kevin.epacms.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.kevin.epacms.constant.CommonConstant;
import com.kevin.epacms.entity.Record;
import com.kevin.epacms.entity.User;
import com.kevin.epacms.entity.dto.UserDto;
import com.kevin.epacms.entity.vo.ConditionVo;
import com.kevin.epacms.mapper.RecordMapper;
import com.kevin.epacms.service.RecordService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.kevin.epacms.util.PageList;
import com.kevin.epacms.util.Result;
import com.kevin.epacms.util.SearchUtil;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author kevin
 * @since 2022-11-10
 */
@Service
public class RecordServiceImpl extends ServiceImpl<RecordMapper, Record> implements RecordService {

    @Override
    public Result addRecord(Record record) {
        record.setTime(LocalDateTime.now());
        return save(record) ? Result.ok(CommonConstant.SUCCESS) : Result.fail(CommonConstant.FAIL);
    }

    @Override
    public Result delRecord(Long id) {
        return removeById(id) ? Result.ok(CommonConstant.SUCCESS) : Result.fail(CommonConstant.FAIL);
    }

    @Override
    public Result delBatchRecords(String recordIdsStr) {
        List<Long> ids = Arrays.stream(recordIdsStr.split(StrUtil.COMMA)).map(Long::parseLong).collect(Collectors.toList());
        return removeByIds(ids) ? Result.ok(CommonConstant.SUCCESS) : Result.fail(CommonConstant.FAIL);
    }

    @Override
    public Result isRecord(Long uid) {
        QueryWrapper<Record> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("uid", uid)
                .apply("DATE_FORMAT( time, '%Y-%m-%d' ) = CURDATE()");
        boolean flag = baseMapper.selectCount(queryWrapper) > 0;
        return flag ? Result.ok(CommonConstant.SUCCESS) : Result.fail(CommonConstant.FAIL);
    }

    @Override
    public Result getRecordsPageByCondition(Integer currentPage, Integer pageSize, List<ConditionVo> conditions) {
        QueryWrapper<Record> queryWrapper = SearchUtil.parseWhereSql(conditions);
        queryWrapper.orderByDesc("time");
        IPage<Record> recordByCondition = baseMapper.getRecordByCondition(new Page<>(currentPage, pageSize), queryWrapper);
        PageList recordPageList = new PageList(recordByCondition);
        return Result.ok(recordPageList);
    }
}
